package sskj.regulatory.presentation.screen.sitevideo.siteveiw

import android.os.Looper
import android.widget.Toast
import com.hikvision.sdk.VMSNetSDK
import com.hikvision.sdk.consts.SDKConstant
import com.hikvision.sdk.net.bean.LoginData
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness
import kotlinx.android.synthetic.main.fragment_sitevideo_view.view.*
import sskj.regulatory.App
import sskj.regulatory.R
import sskj.regulatory.data.network.ApiConstants
import sskj.regulatory.domain.entity.sitevideo.Site
import sskj.regulatory.presentation.base_mvp.base.BaseFragment
import sskj.regulatory.presentation.utils.delegates.bundle
import sskj.regulatory.presentation.utils.delegates.bundleWith
import javax.inject.Inject
import android.animation.ObjectAnimator
import android.app.Dialog
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import com.anthonyfdev.dropdownview.DropDownView
import com.hikvision.sdk.utils.FileUtils
import kotlinx.android.synthetic.main.item_sitevideochange.view.*
import kotlinx.android.synthetic.main.item_sitevideochange_qingxidu.view.*
import sskj.regulatory.domain.entity.sitevideo.SiteVideo
import sskj.regulatory.presentation.adapter.DropDownAdapter
import sskj.regulatory.presentation.adapter.DropDownAdapter.ViewActions
import android.view.WindowManager
import android.view.LayoutInflater
import sskj.regulatory.presentation.utils.UIUtils


class SiteViewFragment : BaseFragment<SiteViewContract.View, SiteViewContract.Presenter>(), SiteViewContract.View {

    companion object {
        fun getBundle(site: Site?) = "site" bundleWith site
    }

    @Inject
    lateinit var mPresenter: SiteViewPresenter

    override fun initPresenter() = mPresenter

    override fun injectDependencies() = activityComponent.inject(this)

    override fun onBackPressed(): Boolean{
        stopVideo()
        return true
    }

    val site: Site by bundle()

    override fun translucentFull() = false

    var msiteVideos : List<SiteVideo>? = null

    var jkbm : String? = null

    override val layoutResId: Int = R.layout.fragment_sitevideo_view
    var mGestureDetector: GestureDetector? = null
    var mScaleGestureDetector: ScaleGestureDetector? = null

    protected val FLIP_DISTANCE = 130
    var islongpressed = false
    var isturning = false
    var iszoom = false
    var isVideoStoped=false

    private var adapter: DropDownAdapter? = null
    private var headerChevronIV: ImageView? = null
    private var selectedStandId: Int = 0
    private var selectedStandTitleTV: TextView? = null
    private var collapsedView: View? = null
    private var dropDownView: DropDownView? = null
    private var expandedView: View? = null
    private var recyclerView: RecyclerView? = null

    override fun initView() {
        initToolBar()
        initData()
        initDropDownView()
        initRecyclerView()
        inittouch()
        initEvent()
        loginAndplayLiveVideo(SDKConstant.LiveSDKConstant.SUB_STREAM)
    }

    private fun initEvent() {

//        mCacheView.vSlidingDrawer.setOnDrawerOpenListener {
//            mCacheView.ivSlide.setImageResource(R.mipmap.ic_double_down)
//        }
//        mCacheView.vSlidingDrawer.setOnDrawerCloseListener {
//            mCacheView.ivSlide.setImageResource(R.mipmap.ic_double_up)
//        }

        mCacheView.mCloudControlLayout.setOnTouchListener{ _, motionEvent ->
            val detectedUp = motionEvent.getAction() === MotionEvent.ACTION_UP
            if (!mGestureDetector!!.onTouchEvent(motionEvent) && detectedUp) {
                onUp(motionEvent)
            }
            mGestureDetector!!.onTouchEvent(motionEvent)
            mScaleGestureDetector!!.onTouchEvent(motionEvent)
        }

        mCacheView.cloudControlImage.setOnClickListener{
            mCacheView.siteVideoChangeAreaQingxidu.visibility=View.GONE
            mCacheView.setqingxidu.setImageResource(R.mipmap.ic_mirror)
            mCacheView.siteVideoChangeArea.visibility=View.VISIBLE
            if(mCacheView.cloudControlImage.drawable.current.constantState==resources.getDrawable(R.mipmap.ic_cloudcontrol).constantState){
                mCacheView.cloudControlImage.setImageResource(R.mipmap.ic_cloudcontrol2)
                mCacheView.mCloudControlLayout.visibility=View.VISIBLE
            }else{
                mCacheView.cloudControlImage.setImageResource(R.mipmap.ic_cloudcontrol)
                mCacheView.mCloudControlLayout.visibility=View.GONE
            }

        }

        mCacheView.zidongxunhang.setOnClickListener{
            mCacheView.cloudControlImage.setImageResource(R.mipmap.ic_cloudcontrol2)
            mCacheView.mCloudControlLayout.visibility=View.VISIBLE

            if(mCacheView.zidongxunhang.drawable.current.constantState==resources.getDrawable(R.mipmap.ic_rotate).constantState){
                mCacheView.zidongxunhang.setImageResource(R.mipmap.ic_rotate2)
                cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,29)
            }else{
                mCacheView.zidongxunhang.setImageResource(R.mipmap.ic_rotate)
                cloudControl(SDKConstant.PTZCommandConstant.ACTION_STOP,29)
            }

        }

        mCacheView.tiaojiaoju.setOnClickListener{
            mCacheView.tiaojiaoju.setImageResource(R.mipmap.ic_forest2)
            showControlDialog(1)
        }

        mCacheView.jujiao.setOnClickListener{
            mCacheView.jujiao.setImageResource(R.mipmap.ic_liangfangkuai2)
            showControlDialog(2)
        }

        mCacheView.tiaoguangquan.setOnClickListener{
            mCacheView.tiaoguangquan.setImageResource(R.mipmap.ic_renzhebiao2)
            showControlDialog(3)
        }

        mCacheView.yuzhidian.setOnClickListener{
            UIUtils.showToast(context,"设置预制点功能还在开发中")
        }

        mCacheView.screenShot.setOnClickListener{
            val opt = VMSNetSDK.getInstance().captureLiveOpt(1, FileUtils.getPictureDirPath().absolutePath,
                    "Picture" + System.currentTimeMillis() + ".jpg")
            when (opt) {
                SDKConstant.LiveSDKConstant.SD_CARD_UN_USABLE -> UIUtils.showToast(context,"SD卡不可用")
                SDKConstant.LiveSDKConstant.SD_CARD_SIZE_NOT_ENOUGH -> UIUtils.showToast(context,"SD卡空间不足")
                SDKConstant.LiveSDKConstant.CAPTURE_FAILED -> UIUtils.showToast(context,"抓拍失败")
                SDKConstant.LiveSDKConstant.CAPTURE_SUCCESS -> UIUtils.showToast(context,"抓拍成功")
            }
        }

        mCacheView.videoding.setOnClickListener{
            if(mCacheView.videoding.drawable.current.constantState==resources.getDrawable(R.mipmap.ic_videocamera).constantState){
                val recordOpt = VMSNetSDK.getInstance().startLiveRecordOpt(1, FileUtils.getVideoDirPath().absolutePath, "Video" + System.currentTimeMillis() + ".mp4")
                when (recordOpt) {
                    SDKConstant.LiveSDKConstant.SD_CARD_UN_USABLE -> UIUtils.showToast(context, "SD卡不可用")
                    SDKConstant.LiveSDKConstant.SD_CARD_SIZE_NOT_ENOUGH -> UIUtils.showToast(context,"SD卡空间不足")
                    SDKConstant.LiveSDKConstant.RECORD_FAILED -> {
                        UIUtils.showToast(context,"启动录像失败")
                    }
                    SDKConstant.LiveSDKConstant.RECORD_SUCCESS -> {
                        UIUtils.showToast(context,"启动录像成功")
                        mCacheView.videoding.setImageResource(R.mipmap.ic_videocamera2)
                    }
                }

            }else{
                VMSNetSDK.getInstance().stopLiveRecordOpt(1)
                UIUtils.showToast(context,"停止录像成功")
                mCacheView.videoding.setImageResource(R.mipmap.ic_videocamera)
            }
        }

        mCacheView.setqingxidu.setOnClickListener{
            if(mCacheView.setqingxidu.drawable.current.constantState==resources.getDrawable(R.mipmap.ic_mirror).constantState){
                mCacheView.cloudControlImage.setImageResource(R.mipmap.ic_cloudcontrol)
                mCacheView.mCloudControlLayout.visibility=View.GONE

                mCacheView.siteVideoChangeArea.visibility=View.GONE
                //替换图标颜色
                mCacheView.setqingxidu.setImageResource(R.mipmap.ic_mirror2)

                mCacheView.siteVideoChangeAreaQingxidu.visibility=View.VISIBLE
            }
        }

        mCacheView.voiceSwitch.setOnClickListener{
            if(mCacheView.voiceSwitch.drawable.current.constantState==resources.getDrawable(R.mipmap.ic_turnoffvoice2).constantState){
                val ret = VMSNetSDK.getInstance().startLiveAudioOpt(1)
                if (!ret) {
                    UIUtils.showToast(context,"开启音频失败")
                } else {
                    // 开启音频成功，并不代表一定有声音，需要设备开启声音。
                    UIUtils.showToast(context,"开启音频成功")
                    mCacheView.voiceSwitch.setImageResource(R.mipmap.ic_turnoffvoice)
                }
            }else{
                val audioOpt = VMSNetSDK.getInstance().stopLiveAudioOpt(1)
                if (audioOpt) {
                    UIUtils.showToast(context,"关闭音频成功")
                    mCacheView.voiceSwitch.setImageResource(R.mipmap.ic_turnoffvoice2)
                }
            }
        }

        mCacheView.liuchangarea.setOnClickListener{
            stopVideo()
            loginAndplayLiveVideo(SDKConstant.LiveSDKConstant.SUB_STREAM)
        }

        mCacheView.biaoqingarea.setOnClickListener{
            stopVideo()
            loginAndplayLiveVideo(SDKConstant.LiveSDKConstant.SUB_STANDARD_STREAM)
        }

        mCacheView.gaoqingarea.setOnClickListener{
            stopVideo()
            loginAndplayLiveVideo(SDKConstant.LiveSDKConstant.MAIN_HIGH_STREAM)
        }
    }

    private fun initRecyclerView() {

    }


    private fun initDropDownView(){
        setupViews()
        setupList()
        mCacheView.drop_down_view.setHeaderView(collapsedView!!)
        mCacheView.drop_down_view.setExpandedView(expandedView!!)
        val dropDownListener = object : DropDownView.DropDownListener {
            override fun onExpandDropDown() {
                adapter!!.notifyDataSetChanged()
                ObjectAnimator.ofFloat(headerChevronIV, View.ROTATION.name, 180f).start()
            }

            override fun onCollapseDropDown() {
                ObjectAnimator.ofFloat(headerChevronIV, View.ROTATION.name, -180f, 0f).start()
            }
        }

        mCacheView.drop_down_view.dropDownListener = dropDownListener
    }

    private fun initToolBar() {
        mCacheView.vTopBar.setTitle(site.name)

        mCacheView.vTopBar.addLeftBackImageButton().setOnClickListener {
            VMSNetSDK.getInstance().stopLiveOpt(1)
            popBackStack()
        }
    }

    private fun initData() {
        msiteVideos = site.siteVideos
        mCacheView.engnamedisplay.text = site.name
    }

    private fun loginAndplayLiveVideo(streamType:Int){
        VMSNetSDK.getInstance().Login(ApiConstants.HIK_ENDPOINT, "admin", "hik12345+", App.getMacAddress(), object : OnVMSNetSDKBusiness() {
            override fun onFailure() {
                UIUtils.showToast(context,"登录错误")
            }

            override fun onStatusCallback(var1: Int) {
                println("状态码:"+var1)
            }

            override fun onSuccess(obj: Any?) {
                if (obj is LoginData) {
//                    mHandler.sendEmptyMessage(LOGIN_SUCCESS)
//                    //存储登录数据
//                    TempDatas.getIns().setLoginData(obj as LoginData?)
//                    TempDatas.getIns().setLoginAddr(url)
//                    val editor = sharedPreferences.edit()
//                    editor.putString(Constants.USER_NAME, mUserEdit.getText().toString().trim({ it <= ' ' }))
//                    editor.putString(Constants.PASSWORD, mPsdEdit.getText().toString().trim({ it <= ' ' }))
//                    editor.putString(Constants.ADDRESS_NET, mUrlEdit.getText().toString().trim({ it <= ' ' }))
//                    editor.apply()
//                    //解析版本号
//                    val appVersion = obj.version
//                    SDKUtil.analystVersionInfo(appVersion)
//                    //跳转资源列表页面
//                    val intent = Intent(this@LoginActivity, ResourceListActivity::class.java)
//                    intent.putExtra(Constants.IntentKey.GET_ROOT_NODE, true)
//                    startActivity(intent)

                    //根据播放的视频源质量类型将相应的TextView变成红色
                    setqingxidutextviewblack()
                    when (streamType) {
                        SDKConstant.LiveSDKConstant.MAIN_HIGH_STREAM -> mCacheView.gaoqingareatextview.setTextColor(Color.RED)
                        SDKConstant.LiveSDKConstant.SUB_STANDARD_STREAM -> mCacheView.biaoqingareatextview.setTextColor(Color.RED)
                        SDKConstant.LiveSDKConstant.SUB_STREAM -> mCacheView.liuchangareatextview.setTextColor(Color.RED)
                    }

                    object : Thread() {
                        override fun run() {
                            Looper.prepare()
                            playVideo(streamType)
                            Looper.loop()
                        }
                    }.start()
                }
            }
        })
    }

    private fun setqingxidutextviewblack(){
        mCacheView.gaoqingareatextview.setTextColor(Color.BLACK)
        mCacheView.biaoqingareatextview.setTextColor(Color.BLACK)
        mCacheView.liuchangareatextview.setTextColor(Color.BLACK)
    }

    private fun playVideo(streamType:Int){
        VMSNetSDK.getInstance().startLiveOpt(1, jkbm, mCacheView.vCustomSurfaceView
                , streamType, object : OnVMSNetSDKBusiness() {
            override fun onFailure() {
                UIUtils.showToast(context,"播放失败")
            }

            override fun onSuccess(obj: Any?) {
                UIUtils.showToast(context,"播放成功")
            }
        })
    }

    private fun stopVideo(){
        if(!isVideoStoped){
            isVideoStoped = VMSNetSDK.getInstance().stopLiveOpt(1)
        }
    }

    private fun cloudControl(action:String,command:Int){
        VMSNetSDK.getInstance().sendPTZCtrlCommand(1,true, action,command,256,object : OnVMSNetSDKBusiness(){
            override fun onFailure() {
                Toast.makeText(context, "云台控制失败", Toast.LENGTH_SHORT).show()
            }

            override fun onSuccess(obj: Any?) {
                Toast.makeText(context, "云台控制成功", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun onUp(e: MotionEvent){
        islongpressed=false
        cloudControl(SDKConstant.PTZCommandConstant.ACTION_STOP,23)
        isturning=false
        hideenControlImage()
    }

    private fun inittouch(){
        mGestureDetector = GestureDetector(context, object : GestureDetector.OnGestureListener {
            override fun onDown(e: MotionEvent): Boolean {
                return true
            }

            override fun onShowPress(e: MotionEvent) {

            }

            override fun onSingleTapUp(e: MotionEvent): Boolean {
                return false
            }

            override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
                if(!isturning){
                    if (e1.getX() - e2.getX() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) > 0.5
                            && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) < 2 && e2.getY() - e1.getY() > 0) {
                        isturning=true
                        mCacheView.mBottomLeftImage.visibility=View.VISIBLE
                        mCacheView.mBottomLeftImage.setMovieResource(R.mipmap.ic_arrow_bottomleft)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,27)
                        return true
                    }
                    if (e1.getX() - e2.getX() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) > 0.5
                            && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) < 2 && e2.getY() - e1.getY() < 0) {
                        isturning=true
                        mCacheView.mTopLeftImage.visibility=View.VISIBLE
                        mCacheView.mTopLeftImage.setMovieResource(R.mipmap.ic_arrow_topleft)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,25)
                        return true
                    }
                    if (e2.getX() - e1.getX() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) > 0.5
                            && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) < 2 && e2.getY() - e1.getY() > 0) {
                        isturning=true
                        mCacheView.mBottomRightImage.visibility=View.VISIBLE
                        mCacheView.mBottomRightImage.setMovieResource(R.mipmap.ic_arrow_bottomright)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,28)
                        return true
                    }
                    if (e2.getX() - e1.getX() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) > 0.5
                            && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) < 2 && e2.getY() - e1.getY() < 0) {
                        isturning=true
                        mCacheView.mTopRightImage.visibility=View.VISIBLE
                        mCacheView.mTopRightImage.setMovieResource(R.mipmap.ic_arrow_topright)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,26)
                        return true
                    }
                    if (e1.getX() - e2.getX() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) > 2) {
                        isturning=true
                        mCacheView.mCenterLeftImage.visibility=View.VISIBLE
                        mCacheView.mCenterLeftImage.setMovieResource(R.mipmap.ic_arrow_left)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,23)
                        return true
                    }
                    if (e2.getX() - e1.getX() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) > 2) {
                        isturning=true
                        mCacheView.mCenterRightImage.visibility=View.VISIBLE
                        mCacheView.mCenterRightImage.setMovieResource(R.mipmap.ic_arrow_right)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,24)
                        return true
                    }
                    if (e1.getY() - e2.getY() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) < 0.5) {
                        isturning=true
                        mCacheView.mTopCenterImage.visibility=View.VISIBLE
                        mCacheView.mTopCenterImage.setMovieResource(R.mipmap.ic_arrow_up)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,21)
                        return true
                    }
                    if (e2.getY() - e1.getY() > FLIP_DISTANCE && Math.abs(e1.getX() - e2.getX()) / Math.abs(e1.getY() - e2.getY()) < 0.5) {
                        isturning=true
                        mCacheView.mBottomCenterImage.visibility=View.VISIBLE
                        mCacheView.mBottomCenterImage.setMovieResource(R.mipmap.ic_arrow_down)
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,22)
                        return true
                    }
                }
                return false
            }

            override fun onLongPress(e: MotionEvent) {
                islongpressed=true
            }

            override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
                return false
            }
        })
        mScaleGestureDetector = ScaleGestureDetector(context, object :ScaleGestureDetector.OnScaleGestureListener{
            override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
                return true
            }

            override fun onScaleEnd(detector: ScaleGestureDetector?) {
                iszoom=false
                hideenControlImage()
            }

            override fun onScale(detector: ScaleGestureDetector?): Boolean {
                val scaleFactor = detector!!.getScaleFactor()
                if(!iszoom){
                    if(scaleFactor<1.0){
                        println("缩小")
                        isturning=true  //放大缩小时不允许摄像头转动
                        iszoom=true
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,12)
                    }
                    if(scaleFactor>1.0){
                        println("放大")
                        isturning=true  //放大缩小时不允许摄像头转动
                        iszoom=true
                        cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,11)
                    }
                }
                return false
            }

        })
    }

    private fun setupViews() {
        dropDownView = mCacheView.findViewById(R.id.drop_down_view)
        collapsedView = LayoutInflater.from(context).inflate(R.layout.view_my_drop_down_header, null, false)
        expandedView = LayoutInflater.from(context).inflate(R.layout.view_my_drop_down_expanded, null, false)

        selectedStandTitleTV = collapsedView!!.findViewById(R.id.selected_stand_title)
        recyclerView = expandedView!!.findViewById(R.id.recyclerView)
        headerChevronIV = collapsedView!!.findViewById(R.id.chevron_image)
    }


    val viewActions = object : ViewActions {
        override fun getSelectedStand(): Int {
            return selectedStandId
        }

        override fun setSelectedStand(standId: Int) {
            selectedStandTitleTV!!.text=getStandTitle(standId)
            selectedStandId = standId
        }


        override fun collapseDropDown() {
            dropDownView!!.collapseDropDown()
        }

        override fun getStandTitle(standId: Int): String {
            var title = ""
            var i=0
            for(siteVideo in msiteVideos!!){
                if (standId==i) {
                    title = siteVideo.cameraName.toString()
                    jkbm = siteVideo.sysCode
                }
                i++
            }
            return title
        }

        override fun getItemCount(): Int {
            return msiteVideos!!.size
        }

        override fun stopAndPlayLiveVideo(){
            stopVideo()
            loginAndplayLiveVideo(SDKConstant.LiveSDKConstant.SUB_STREAM)
        }
    }

    private fun setupList() {
        viewActions.setSelectedStand(0)
        adapter = DropDownAdapter(viewActions)
        recyclerView!!.layoutManager=LinearLayoutManager(context)
        recyclerView!!.adapter=adapter
    }

    private fun hideenControlImage(){
        mCacheView.mTopLeftImage.visibility=View.GONE
        mCacheView.mTopCenterImage.visibility=View.GONE
        mCacheView.mTopRightImage.visibility=View.GONE
        mCacheView.mCenterLeftImage.visibility=View.GONE
        mCacheView.mCenterCenterImage.visibility=View.GONE
        mCacheView.mCenterRightImage.visibility=View.GONE
        mCacheView.mBottomLeftImage.visibility=View.GONE
        mCacheView.mBottomCenterImage.visibility=View.GONE
        mCacheView.mBottomRightImage.visibility=View.GONE
    }

    private fun showControlDialog(type:Int){
        val mDialog = Dialog(context)
        //去除标题栏
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        //2.填充布局
        val inflater = LayoutInflater.from(context)
        var view = 0
        when (type) {
            1 -> view = R.layout.item_sitevideo_dialog
            2 -> view = R.layout.item_sitevideo_dialog_jujiao
            3 -> view = R.layout.item_sitevideo_dialog_guangquan
        }
        val dialogView = inflater.inflate(view, null)
        //将自定义布局设置进去
        mDialog.setContentView(dialogView)
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        val lp = WindowManager.LayoutParams()
        val window = mDialog.window
        window.setDimAmount(0f)     //取消遮罩
        lp.copyFrom(window.attributes)
        lp.width = 800
        lp.height = 300
        lp.y = 300 // 新位置Y坐标
        lp.alpha = 0.7f // 透明度
        window.attributes=lp
        mDialog.setOnDismissListener{
            when (type) {
                1 -> mCacheView.tiaojiaoju.setImageResource(R.mipmap.ic_forest)
                2 -> mCacheView.jujiao.setImageResource(R.mipmap.ic_liangfangkuai)
                3 -> mCacheView.tiaoguangquan.setImageResource(R.mipmap.ic_renzhebiao)
            }
        }
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show()
        when (type) {
            1 -> touchtiaojiaoju(mDialog)
            2 -> touchtiaojujiao(mDialog)
            3 -> touchtiaoguangquan(mDialog)
        }
    }

    private fun touchtiaojiaoju(mDialog:Dialog){
        mDialog.findViewById<ImageView>(R.id.tiaojiaojujia).setOnTouchListener{ _, motionEvent ->
            isturning=true  //放大缩小时不允许摄像头转动
            iszoom=true
            when(motionEvent.action){
                MotionEvent.ACTION_DOWN -> cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,11)
                MotionEvent.ACTION_UP -> onUp(motionEvent)
                MotionEvent.ACTION_CANCEL -> onUp(motionEvent)
            }
            true
        }

        mDialog.findViewById<ImageView>(R.id.tiaojiaojujian).setOnTouchListener{ _, motionEvent ->
            isturning=true  //放大缩小时不允许摄像头转动
            iszoom=true
            when(motionEvent.action){
                MotionEvent.ACTION_DOWN -> cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,12)
                MotionEvent.ACTION_UP -> onUp(motionEvent)
                MotionEvent.ACTION_CANCEL -> onUp(motionEvent)
            }
            true
        }
    }

    private fun touchtiaojujiao(mDialog:Dialog){
        mDialog.findViewById<ImageView>(R.id.tiaojujiaojia).setOnTouchListener{ _, motionEvent ->
            isturning=true  //放大缩小时不允许摄像头转动
            iszoom=true
            when(motionEvent.action){
                MotionEvent.ACTION_DOWN -> cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,13)
                MotionEvent.ACTION_UP -> onUp(motionEvent)
                MotionEvent.ACTION_CANCEL -> onUp(motionEvent)
            }
            true
        }

        mDialog.findViewById<ImageView>(R.id.tiaojujiaojian).setOnTouchListener{ _, motionEvent ->
            isturning=true  //放大缩小时不允许摄像头转动
            iszoom=true
            when(motionEvent.action){
                MotionEvent.ACTION_DOWN -> cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,14)
                MotionEvent.ACTION_UP -> onUp(motionEvent)
                MotionEvent.ACTION_CANCEL -> onUp(motionEvent)
            }
            true
        }
    }

    private fun touchtiaoguangquan(mDialog:Dialog){
        mDialog.findViewById<ImageView>(R.id.tiaoguangquanjia).setOnTouchListener{ _, motionEvent ->
            isturning=true  //放大缩小时不允许摄像头转动
            iszoom=true
            when(motionEvent.action){
                MotionEvent.ACTION_DOWN -> cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,15)
                MotionEvent.ACTION_UP -> onUp(motionEvent)
                MotionEvent.ACTION_CANCEL -> onUp(motionEvent)
            }
            true
        }

        mDialog.findViewById<ImageView>(R.id.tiaoguangquanjian).setOnTouchListener{ _, motionEvent ->
            isturning=true  //放大缩小时不允许摄像头转动
            iszoom=true
            when(motionEvent.action){
                MotionEvent.ACTION_DOWN -> cloudControl(SDKConstant.PTZCommandConstant.ACTION_START,16)
                MotionEvent.ACTION_UP -> onUp(motionEvent)
                MotionEvent.ACTION_CANCEL -> onUp(motionEvent)
            }
            true
        }
    }

}